package icu.cqcai.xinsi.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云OSS文件上传服务
 */
@Service
public class OssService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 上传文件到阿里云OSS
     * @param file 要上传的文件
     * @return 文件的访问URL
     */
    public String uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 生成文件名
            String fileName = generateFileName(file.getOriginalFilename());
            
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
            
            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            
            // 构建文件访问URL
            String fileUrl = endpoint.replace("https://", "https://" + bucketName + ".") + "/" + fileName;
            
            System.out.println("文件上传成功到OSS: " + fileUrl);
            System.out.println("原始文件名: " + file.getOriginalFilename());
            System.out.println("文件大小: " + file.getSize() + " bytes");
            
            return fileUrl;
            
        } catch (IOException e) {
            System.err.println("文件上传失败: " + e.getMessage());
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }

    /**
     * 生成唯一的文件名
     * @param originalFilename 原始文件名
     * @return 生成的文件名
     */
    private String generateFileName(String originalFilename) {
        // 获取文件扩展名
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        // 生成日期路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());
        
        // 生成UUID文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        
        // 组合文件路径：resume/2025/06/15/uuid.pdf
        return "resume/" + datePath + "/" + uuid + extension;
    }

    /**
     * 删除OSS中的文件
     * @param fileUrl 文件URL
     */
    public void deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return;
        }
        
        try {
            // 从URL中提取文件key
            String bucketDomain = "https://" + bucketName + "." + endpoint.replace("https://", "");
            if (!fileUrl.startsWith(bucketDomain)) {
                System.out.println("文件URL格式不正确，无法删除: " + fileUrl);
                return;
            }
            
            String fileKey = fileUrl.substring(bucketDomain.length() + 1);
            
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            try {
                ossClient.deleteObject(bucketName, fileKey);
                System.out.println("文件删除成功: " + fileUrl);
            } finally {
                ossClient.shutdown();
            }
            
        } catch (Exception e) {
            System.err.println("文件删除失败: " + e.getMessage());
        }
    }
} 